(function (fruit, util, global,dom) {

    fruit.ui.define("fruit.ui.CodeViewer", {
        view:{
            props:{
                'class':'f-codeviewer'
            },
            content:[
                {
                    name:"codeview",
                    props:{
                        'class':'f-codeviewer-code'
                    }
                },
                {
                    name:"btn",
                    type:"fruit.ui.Button",
                    props:{
                        text:"Run",
                        theme:"primary",
                        'class':'f-codeviewer-btn'
                    },
                    events:{
                        'click':'#_run'
                    }
                },
                {
                    content:{
                        name:"preview",
                        tag:"iframe"
                    }
                }
            ]
        },
        properties:{
            code:{
                observable:true
            }
        },
        methods:{
            onInit:function () {
                if (CodeMirror === undefined || js_beautify === undefined) {
                    fruit.log("Please link codemirror.js/codemirror.css and beautify.js");
                    return false;
                }
                this._printCode();
            },
            _printCode:function () {
                var code = this.code();
                var codeview = this.$("codeview");
                var editor = this.editor = CodeMirror(codeview._element, {
                    value:js_beautify(code),
                    mode:"javascript",
                    theme:'night'
                });
                setTimeout(function () {
                    editor.refresh();
                });
            },
            _run:function () {
                var previewFrame = this.$("preview")._element;
                var previewDoc = previewFrame.contentDocument || previewFrame.contentWindow.document;
                var script = this.editor.getDoc().getValue();
                //todo remove $
                var fruitjs = $("script[src*='fruit.js']")[0].outerHTML;
                var fruitcss = $("link[href*='futurama.css']")[0].outerHTML;

                previewDoc.open();
                previewDoc.write(fruitcss);
                previewDoc.write(fruitjs);
                previewDoc.write('<script>' + script+ '<\/script>');
                previewDoc.close();

                this.$("preview").addClass("f-codeviewer-open");
            }

        }
    });
})(fruit, fruit.util, fruit.global,fruit.dom);